package cn.ifafu.ifafu.util;

import android.content.Context;
import android.graphics.Bitmap;
import android.net.Uri;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.databinding.BindingAdapter;

public final class BindingAdapters {

    private BindingAdapters() {
    }

    @BindingAdapter("visibleGoneWhen")
    public static void setVisibleGoneWhen(View view, @Nullable Boolean gone) {
        view.setVisibility(Boolean.TRUE.equals(gone) ? View.GONE : View.VISIBLE);
    }

    @BindingAdapter("isVisible")
    public static void setIsVisible(View view, @Nullable Boolean isVisible) {
        view.setVisibility(Boolean.TRUE.equals(isVisible) ? View.VISIBLE : View.GONE);
    }

    @BindingAdapter("srcBitmap")
    public static void setSrcBitmap(ImageView view, @Nullable Bitmap bitmap) {
        view.setImageBitmap(bitmap);
    }

    @BindingAdapter("android:visibleWhen")
    public static void setVisibleWhen(View view, @Nullable Boolean visible) {
        view.setVisibility(Boolean.TRUE.equals(visible) ? View.VISIBLE : View.GONE);
    }

    @BindingAdapter("android:goneWhen")
    public static void setGoneWhen(View view, @Nullable Boolean gone) {
        view.setVisibility(Boolean.TRUE.equals(gone) ? View.GONE : View.VISIBLE);
    }

    @BindingAdapter("android:invisibleWhen")
    public static void setInvisibleWhen(View view, @Nullable Boolean invisible) {
        view.setVisibility(Boolean.TRUE.equals(invisible) ? View.INVISIBLE : View.VISIBLE);
    }

    @BindingAdapter("android:hideKeyboardOnInputDone")
    public static void hideKeyboardOnInputDone(EditText editText, @Nullable Boolean enabled) {
        if (!Boolean.TRUE.equals(enabled)) {
            return;
        }
        TextView.OnEditorActionListener listener = (textView, actionId, keyEvent) -> {
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                editText.clearFocus();
                InputMethodManager imm = (InputMethodManager) editText.getContext()
                        .getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
                }
            }
            return false;
        };
        editText.setOnEditorActionListener(listener);
    }
}
